package net.my.msn.web;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import net.my.msn.service.UserService;
import net.my.msn.web.forms.Registration;

@Controller
@RequestMapping("/registration")
/* @SessionAttributes("user") */
public class RegistrationController {
	@Autowired
	private UserService userService;

	@RequestMapping(method = RequestMethod.GET)
	public String showUserForm(ModelMap model) {
		Registration reg = new Registration();
		model.addAttribute(reg);
		return "registration";
	}

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView onSubmit(
			@ModelAttribute("registration") @Valid Registration reg,
			BindingResult result) {
		ModelMap modelMap = new ModelMap();
		boolean passwordsCheck = reg.getPassword().equals(reg.getConfirm());
		modelMap.addAttribute("checkPassword", passwordsCheck);
		modelMap.addAttribute("checkUsername",
				userService.userByName(reg.getUsername()));
		modelMap.addAttribute("checkEmail",
				userService.userByEmail(reg.getEmail()));
		if ((userService.userCheck(reg)) && (result.hasErrors() == false)
				&& (passwordsCheck)) {
			userService.addUser(reg);
			return new ModelAndView("redirect:login");
		} else
			return new ModelAndView("registration", modelMap);
	}
}
